package middleware

import (
	"bgs/util"
	"context"
	"go.uber.org/zap"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

func injectRequestID(ctx context.Context, reqIDFromMetadata []string) context.Context {
	var reqID string
	if (len(reqIDFromMetadata) == 0) {
		reqID = uuid.New().String()
	} else {
		reqID = reqIDFromMetadata[0]
	}
	return context.WithValue(ctx, util.RequestID{}, reqID)
}

// UnaryRequestIDInterceptor add request_id
func UnaryRequestIDInterceptor(slog *zap.SugaredLogger) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		md, ok := metadata.FromIncomingContext(ctx)
		if (ok) {
			ctx = injectRequestID(ctx, md.Get("x-request-id"))	
		}

		reqID := ctx.Value(util.RequestID{})
		slog.Infof("enter-requestID::->%s", reqID)
		
		return handler(ctx, req)
	}
}